package com.waigoulin.domain.order.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.waigoulin.domain.order.adapter.port.IPaymentPort;
import com.waigoulin.domain.order.adapter.port.IProductPort;
import com.waigoulin.domain.order.adapter.repository.IOrderDaoRepository;
import com.waigoulin.domain.order.model.aggregate.CreateOrderAggregate;
import com.waigoulin.domain.order.model.entity.PayOrderEntity;
import com.waigoulin.domain.order.model.valobj.OrderStatusVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

/**
 * @FileName OrderService
 * @Description 抽象订单服务领域层接口实现类的子类 ———— 订单服务领域层接口实现类
 * @Author waigoulin
 * @date 2025-07-31
 **/
@Service
public class OrderService extends AbstractOrderService {

    // 尝试把支付宝的调用放到基础设施层使用
    // 领域层实现
//    @Value("${alipay.notify_url}")
//    private String notifyUrl;
//
//    @Value("${alipay.return_url}")
//    private String returnUrl;
//
//    @Resource
//    private AlipayClient alipayClient;
    // 基础设施层实现
    @Resource
    private IPaymentPort paymentPort;

    public OrderService(IOrderDaoRepository orderDaoRepository, IProductPort productPort) {
        super(orderDaoRepository, productPort);
    }

    @Override
    protected PayOrderEntity doPrepareOrder(String userId, String productId, String productName, String orderId, BigDecimal totalAmount) throws AlipayApiException {
        // 调用基础设施层的支付宝服务
        PayOrderEntity payOrderEntity = paymentPort.createPayment(userId, productId, productName, orderId, totalAmount);

        // 执行更新操作
        orderDaoRepository.updateOrderPayInfo(payOrderEntity);

        // 返回对应的流水单
        return payOrderEntity;
    }

    @Override
    protected void doSaveOrder(CreateOrderAggregate createOrderAggregate) {
        orderDaoRepository.doSaveOrder(createOrderAggregate);
    }

    @Override
    public void changeOrderPaySuccess(String orderId) {
        orderDaoRepository.changeOrderPaySuccess(orderId);
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        return orderDaoRepository.queryNoPayNotifyOrder();
    }

    @Override
    public List<String> queryTimeoutCloseOrderList() {
        return orderDaoRepository.queryTimeoutCloseOrderList();
    }

    @Override
    public boolean changeOrderClose(String orderId) {
        return orderDaoRepository.changeOrderClose(orderId);
    }
}


